package com.open.capacity.sign.service.impl;

import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.model.Sign;
import com.open.capacity.common.model.SignReport;
import com.open.capacity.common.model.SysParam;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.redis.util.RedisUtil;
import com.open.capacity.sign.dao.SignDao;
import com.open.capacity.sign.service.SignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.*;


@Slf4j
@Service
public class signServiceImpl implements SignService {
    @Autowired
    private SignDao signDao;
    @Autowired
    private RedisUtil redisUtil;



//    public RedisUtil getRedisUtil(Sign sign) {
//        redisUtil.set(sign.getLate_time(),"");
//    }

    @Override
    public Result signOut(Sign sign) throws ServiceException {
        try {
            Date d = new Date();
            SimpleDateFormat nowDate = new SimpleDateFormat("yyyy-MM-dd");
            String time = nowDate.format(d);
            sign.setTime(time);
            boolean findDaily = findDaily(sign);
            if (findDaily) {
                Integer signOut;

                boolean have = findSignOut(sign);
                if (have) {
                    return Result.succeed(2, "已签退,不能重复签退");
                } else {
                    SimpleDateFormat nowTime = new SimpleDateFormat("HH:mm:ss");
                    String Signout = nowTime.format(d);
                    sign.setSigout(Signout);
                    Integer outstate = checkedSignOutState(Signout);
                    sign.setOstate(outstate);
                    boolean isHave = findSignInState(sign);
                    if (isHave) {
                        signOut = signDao.editSignOut(sign);
                        if (signOut == 1) {
                            if (outstate == 1) {
                                return Result.succeed(1, "签退成功！");
                            } else if (outstate == 2) {
                                return Result.succeed(3, "早退！");
                            } else {
                                return null;
                            }
                        } else {
                            return Result.succeed(-1, "系统错误！");
                        }
                    } else {
                        signOut = signDao.signOut(sign);
                        if (signOut == 1) {
                            if (outstate == 1) {
                                return Result.succeed(1, "签退成功！");
                            } else if (outstate == 2) {
                                return Result.succeed(3, "早退！");
                            } else {
                                return null;
                            }
                        } else {
                            return Result.succeed(-1, "系统错误！");
                        }
                    }
                }
            }else {
                return Result.succeed(4, "没有写日报！");
            }
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }


    private boolean findDaily(Sign sign) {
        Sign daily=signDao.findDaily(sign);
        boolean have=(daily==null);
        return !have;
    }

    /**
     * 查询是否签退,已签退不能重复签退
     * @param sign
     * @return
     */
    private boolean findSignOut(Sign sign) {
        Sign signModel=signDao.findSignOut(sign);
        boolean have=(signModel==null);
        return !have;
    }

    /**
     * 查询签退时间 早于18点是早退
     * @param signIn
     * @return
     */
    private Integer checkedSignOutState(String signIn) {
        Integer resultState=0;
        String ds=getSigOutTime();
        Integer t=signIn.compareTo(ds);
        if(t==1){
            resultState=1;
        }else {
            resultState=2;
        }
        return resultState;
    }

    private String getSignInTime() {
        String key="signInTime";
        SysParam sysParam=new SysParam();
        sysParam.setKey(key);
        String signInTime=signDao.getParamByKey(sysParam);
        return signInTime;
    }

    private String getSigOutTime() {
        String key="sigOutTime";
        SysParam sysParam=new SysParam();
        sysParam.setKey(key);
        String sigOutTime=signDao.getParamByKey(sysParam);
        return sigOutTime;
    }


    /**
     * 查询签到状态；签到了；没有签到；
     * @param sign
     * @return
     */
    private boolean findSignInState(Sign sign) {
        Integer signModel =signDao.findSignInState(sign);
        boolean isHave=(signModel==1);
        return isHave;
    }

    @Override
    public Result signIn(Sign sign) {
        try {
            Date d = new Date();
            SimpleDateFormat nowDate = new SimpleDateFormat("yyyy-MM-dd");
            String time = nowDate.format(d);
            sign.setTime(time);
            boolean have=findSignOut(sign);
            if (have){
                return Result.succeed(3,"已签退，无法签到");
            }else {
                boolean isHave = findSignIn(sign);
                if (isHave) {
                    return Result.succeed(2, "已签到！");
                } else {
                    SimpleDateFormat nowTime = new SimpleDateFormat("HH:mm:ss");
                    String SignIn = nowTime.format(d);
                    sign.setSignin(SignIn);
                    Integer instate=checkedSignInState(SignIn);
                    sign.setIstate(instate);
                    //检测签到状态：已签到
                    boolean signInStateHave = findSignInState(sign);
                    if (!signInStateHave) {
                        Integer signIn = signDao.signIn(sign);
                        if (signIn == 1) {
                            if (instate == 1) {
                                return Result.succeed(1, "签到成功！");
                            } else if (instate == 2) {
                                return Result.succeed(4, "迟到！");
                            } else {
                                return null;
                            }
                        } else {
                            return Result.succeed(-1, "系统错误！");
                        }
                    }else{
                        Integer signIn = signDao.editSignIn(sign);
                        if (signIn == 1) {
                            if (instate == 1) {
                                return Result.succeed(1, "签到成功！");
                            } else if (instate == 2) {
                                return Result.succeed(4, "迟到！");
                            } else {
                                return null;
                            }
                        } else {
                            return Result.succeed(-1, "系统错误！");
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    private boolean findSignIn(Sign sign) {
        Sign si=signDao.findSignIn(sign);
        boolean isHave=(si==null);
        return !isHave;
    }
//检测签到时间对应的签到状态
    private Integer checkedSignInState(String signIn) {
        Integer resultState=0;
        String ds=getSignInTime();
        Integer t=signIn.compareTo(ds);
        if(t==1){
            resultState=2;
        }else {
            resultState=1;
        }
        return resultState;
    }


    @Override
    public PageResult<Sign> signManage(Map<String, Object> params) {
        try {
            int total = signDao.count(params);
            List<Sign> list = Collections.emptyList();
            if (total > 0) {
                PageUtil.pageParamConver(params, true);
                list = signDao.findList(params);//查询所有用户信息

            }
            return PageResult.<Sign>builder().data(list)
                    .code(0).count((long) total).build();//收集所有数据
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public List<Sign> findAllSigns(Map<String, Object> params) throws ServiceException {
        try {
            List<Sign> signExcels = new ArrayList<>();
            List<Sign> list = signDao.findList(params);

            for (Sign sign : list) {
                Sign signExcel = new Sign();
                BeanUtils.copyProperties(sign, signExcel);
                signExcels.add(signExcel);
            }
            return signExcels;
        } catch (BeansException e) {
            throw new ServiceException(e);
        }
    }




    /** 签到记录修改*/
    @Override
    public Result signUpdate(Sign sign) {
        try {
            Integer update = signDao.signUpdate(sign);
            return Result.succeed(update, "修改成功！");
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /** 签到记录删除*/
    @Override
    public Result signDelete(Sign sign) {
        try {
            Integer update = signDao.signDelete(sign);
            return Result.succeed(update, "删除成功！");
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /** 签到参数查询*/
    @Override
    public List<SysParam> getParamByAttr(SysParam params) throws ServiceException {
        try {
            List<SysParam> signParams = new ArrayList<>();
            List<SysParam> list = signDao.getParamByAttr(params);

            for (SysParam sysParam : list) {
                SysParam signParam = new SysParam();
//                BeanUtils.copyProperties(sysParam, signParam);
                //在此处加入缓存
                signParams.add(sysParam);
            }
            return signParams;
        } catch (BeansException e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public Result signParamUpdate(List<SysParam> list) {
        try {
            Integer update=0;
            for (SysParam p:list){
                update = signDao.signParamUpdate(p);
            }
            return Result.succeed(update, "修改成功！");
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public PageResult<SignReport> signCount(Map<String, Object> params) {
        try {
            int total = signDao.getCount(params);
            List<SignReport> list = Collections.emptyList();
            if (total > 0) {
                PageUtil.pageParamConver(params, true);
                list = signDao.findCountList(params);//查询所有用户信息

            }
            return PageResult.<SignReport>builder().data(list)
                    .code(0).count((long) total).build();//收集所有数据
        } catch (Exception e) {
            throw new ServiceException(e);
        }

    }

    @Override
    public List<SignReport> findAllKaoqin(Map<String, Object> params) {
        try {
            List<SignReport> SignReportExcels = new ArrayList<>();
            List<SignReport> list = signDao.findCountList(params);

            for (SignReport signReport : list) {
                SignReport signReportExcel = new SignReport();
                BeanUtils.copyProperties(signReport, signReportExcel);
                SignReportExcels.add(signReportExcel);
            }
            return SignReportExcels;
        } catch (BeansException e) {
            throw new ServiceException(e);
        }
    }
}
